package 领扣算法.AA中等题.任务调度器1;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;

public class Main {
    public int leastInterval(char[] tasks, int n) {
        HashMap<Character,Integer> middle=new HashMap<>();
        for (char task : tasks) {
            int count=middle.getOrDefault(task,0)+1;
            middle.put(task,count);
        }
        Integer data[]=new Integer[middle.size()];
        middle.values().toArray(data);
        PriorityQueue<int[]> queue=new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o2[1]-o1[1];
            }
        });
        for (int i = 0; i < data.length; i++) {
            queue.add(new int[]{i,data[i]});
        }
        int last=-1;
        int count=0;
        while (!queue.isEmpty())
        {
            int[] d1=queue.poll();
            if (queue.isEmpty()){
                if (last==d1[0]){
                    count+=(n+1)*d1[1];
                }
                else {
                    count+=(n)*(d1[1]-1)+d1[1];
                }
                return count;
            }
            int[] d2=queue.poll();
            count+=2;
            d1[1]-=1;
            d2[1]-=1;
            if (d1[1]!= 0 ){
                queue.add(d1);
            }
            if (d2[1]!= 0){
                queue.add(d2);
            }
        }

        return count;
    }
}
